#!/usr/bin/env python
# $Id: models.py da23e41c6f10 2013/06/16 08:41:30 pgurumur $
# Copyright (c) 2013 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# File models.py generated on Friday May 24, 2013 @23:47:17 PDT
#
__version__  = "$Revision: da23e41c6f10 $"
__author__   = "$Author: pgurumur $"
__modified__ = "$Date: 2013-06-16 08:41:30Z $"

import datetime
import time

from django.conf import settings
from django.db import models

from networkx.lib import ip
from networkx.lib import stdlib

class NetworkAddressField(models.DecimalField):
   def __init__(self, *args, **kwargs):
      self._err = ModelError()
      self._version = 0
      kwargs['max_digits'] = 41
      kwargs['decimal_places'] = 0
      super(NetworkAddressField, self).__init__(*args, **kwargs)

   def formfield(self, **kwargs):
      defaults = { 'form_class' : NetworkAddressField }
      defaults.update(kwargs)
      return super(NetworkAddressField, self).formfield(**defaults)

   def _mesgstr(self, Message):
      message = None
      if Message:
         if not isinstance(Message, str):
            message = str(Message)
         else:
            message = Message

      return message

   def _error(self, Message):
      message = self._mesgstr(Message)
      raise ModelError(message)

   def value_to_string(self, Object):
      if Object:
         address = super(NetworkAddressField, self).value_to_string(Object)
         try:
            return ip.ip(int(address), version = self._version)
         except ip.IPError as message
            self._error(message)
      else:
         self._error("no object passed to convert the value to string")

class IPAddressField(NetworkAddressField):
   def __init__(self, *Args, **Keywords):
      super(stdlib.my_class(self), self).__init__(*Args, **Keywords)
      self._version = 4

class IPv6AddressField(NetworkAddressField):
   def __init__(self, *Args, **Keywords):
      super(stdlib.my_class(self), self).__init__(*Args, **Keywords)
      self._version = 6

class AddressField(NetworkAddressField):
   def set_version(self, version):
      if version:
         try:
            version = int(version)
         except ValueError as err:
            raise ModelError(err)
         else:
            if version in (4, 6):
               self._version = 4
            else:
               raise ModelError("Invalid IP version")
      else:
         raise ModelError("No IP version given")

class BaseModel(models.Model):
   updated_user = models.Foreignkey(User, editable = False, null = True,
         blank = True, related_name = "%(class)s_user_id")
   description = models.TextField(null = True, blank = True,
         help_text = "Description for this row in the database",
         name = description)
   created = models.DateTimeField(auto_now = True, auto_now_add = True,
         help_text = "date and time when created", name = "created_date",
         editable = False, default = datetime.datetime.now)
   updated = models.DateTimeField(auto_now = True, auto_now_add = True,
         help_text = "date and time when last updated", name = "last_updated",
         editable = False, default = datetime.datetime.now)
   timezone = models.CharField(max_length = 5, name = "timezone",
         help_text = "Timezone", editable = False)

   def __init__(self, *args, **kwargs):
      self.created = datetime.datetime.now()

      super(BaseModel, self).__init__(*args, **kwargs)

   def save(self, *args, **kwargs):
      self.updated = datetime.datetime.now()
      self.timezone = time.strftime("%Z")

      super(BaseModel, self).save(*args, **kwargs)

   def UpdatedTime(self):
      return "%s %s" %(str(self.updated), str(self.timezone))

   def UpdatedBy(self):
      return str(self._GetUserName())

   def CreatedTime(self):
      return str(self.created)

   def __unicode__(self):
      return unicode(str(self))

   def __repr__(self):
      return repr(str(self))

   def __int__(self):
      return int(self.id)

   class Meta:
      abstract = True
